package org.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.example.model.user.UserBasic;

import java.util.Calendar;

/**
 * jwt工具类
 */
public class JwtUtils {

    private static final String SING = "YANYJUNXIAN";

    private static final String UserId = "UserId";
    /**
     * 生成token
     */
    public static String GenerateToken(UserBasic userBasic) {

        //token过期时间
        Calendar instance = Calendar.getInstance();
        // 24小时后令牌token失效
        instance.add(Calendar.HOUR,24);
        String token = JWT.create()
                .withClaim(UserId,userBasic.getId())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token是否合法（即是否已过期）
     */
    public static DecodedJWT Verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 解析token,获取其中的有效信息
     */
    public static int GetInfoFromToken(String token) {
        DecodedJWT decodedJWT = JwtUtils.Verify(token);
        return decodedJWT.getClaim(UserId).asInt();
    }
}
